﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace IrisGenerator.Common.Core
{
    public class BindingItem
    {
        public string BindingValue { get; set; }
        public object ObjectToBind { get; set; }

        public static object GetBindingItem(string bindingValue, object objectToBind)
        {
            if (string.IsNullOrEmpty(bindingValue) || objectToBind == null)
                return null;

            string[] objectHierarchy = bindingValue.Split(".".ToCharArray());
            object tmp=objectToBind;
            for (int i = 0; i < objectHierarchy.Length; i++)
            {
                MemberInfo info = GetMemberInfo(tmp, objectHierarchy[i]);
                tmp = GetCurrentObject(tmp, info);
            }
            return tmp;
        }

        public static MemberInfo GetMemberInfo(object objectToLookIn, string MemberToLookFor)
        {
            MemberInfo[] members=objectToLookIn.GetType().GetMember(MemberToLookFor);
            if (members.Length>0)
                return members[0];
            return null;
        }

        public static object GetCurrentObject(object parentObject, MemberInfo value)
        {
            if (parentObject == null || value==null)
                return null;

            FieldInfo field = value as FieldInfo;
            if (field != null)
            {
                return field.GetValue(parentObject);
            }

            PropertyInfo property = value as PropertyInfo;
            if (property != null)
            {
                return property.GetValue(parentObject, null);
            }

            return null;
        }

       
    }
}
